package com.devplatform.util;

import com.devplatform.pojo.Message;
import com.devplatform.service.MessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class MessageUtil {

    private final MessageService messageService;


    //发送账号安全相关消息
    public void sendSecurityMessage(Long userId, String content) {
        String title = "账号安全通知";
        Message message = buildSystemMessage(userId, title, content);
        message.setRelatedId(userId); // 关联用户ID
        messageService.save(message);
    }

    //发送积分变动消息
    public void sendPointsMessage(Long userId, String action, Integer points, Integer currentPoints) {
        String title = "积分变动通知";
        String content = String.format("您因【%s】%s%d积分，当前积分：%d",
                action, points > 0 ? "获得" : "消耗", Math.abs(points), currentPoints);
        Message message = buildSystemMessage(userId, title, content);
        message.setExtraData(String.format("{\"pointsChange\":%d,\"currentPoints\":%d}", points, currentPoints));
        messageService.save(message);
    }

    //发送签到相关消息
    public void sendCheckInMessage(Long userId, Integer points, Integer continuousDays, String rewardTip) {
        String title = "签到成功";
        String content = String.format("签到成功！获得%d积分，已连续签到%d天。%s",
                points, continuousDays, rewardTip);
        Message message = buildSystemMessage(userId, title, content);
        message.setExtraData(String.format("{\"points\":%d,\"continuousDays\":%d}", points, continuousDays));
        messageService.save(message);
    }

    //发送等级变动消息
    public void sendLevelUpMessage(Long userId, Integer oldLevel, Integer newLevel, String levelName) {
        String title = "等级提升";
        String content = String.format("恭喜！您的等级从 Lv.%d 提升到 Lv.%d (%s)",
                oldLevel, newLevel, levelName);
        Message message = buildSystemMessage(userId, title, content);
        message.setExtraData(String.format("{\"oldLevel\":%d,\"newLevel\":%d}", oldLevel, newLevel));
        messageService.save(message);
    }

    //发送商品兑换消息
    public void sendExchangeMessage(Long userId, String goodsName, Integer pointsCost, String orderId) {
        String title = "商品兑换成功";
        String content = String.format("您已成功兑换【%s】，消耗%d积分。订单号：%s",
                goodsName, pointsCost, orderId);
        Message message = buildSystemMessage(userId, title, content);
        message.setExtraData(String.format("{\"goodsName\":\"%s\",\"pointsCost\":%d}", goodsName, pointsCost));
        messageService.save(message);
    }

    //通用系统消息
    public void sendSystemMessage(Long userId, String title, String content, Map<String, Object> extraData) {
        Message message = buildSystemMessage(userId, title, content);
        if (extraData != null && !extraData.isEmpty()) {
            // 简单地将Map转为JSON字符串存储
            StringBuilder extra = new StringBuilder("{");
            for (Map.Entry<String, Object> entry : extraData.entrySet()) {
                extra.append(String.format("\"%s\":\"%s\",", entry.getKey(), entry.getValue()));
            }
            if (extra.length() > 1) {
                extra.deleteCharAt(extra.length() - 1);
            }
            extra.append("}");
            message.setExtraData(extra.toString());
        }
        messageService.save(message);
    }

    //构建基础系统消息对象
    private Message buildSystemMessage(Long userId, String title, String content) {
        Message message = new Message();
        message.setUserId(userId);
        message.setTitle(title);
        message.setContent(content);
        message.setType(1); // 系统消息
        message.setIsRead(0); // 未读
        message.setCreateTime(LocalDateTime.now());
        return message;
    }
}